﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace bio2WF
{
    public partial class Form1 : Form
    {

        private Dictionary<string, Dictionary<string, double>> distanceMatrix;

        public Form1()
        {
            InitializeComponent();
            InitializeWebBrowser();

            wczytajDomyslnaMacierzButton_Click(new object(), new EventArgs());

        }

        private void InitializeWebBrowser()
        {
            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate("http://www.trex.uqam.ca/index.php?action=newick&project=trex");
            // http://iubio.bio.indiana.edu/treeapp/treeprint-form.html
        }



        private void Compute_NJ_Click(object sender, EventArgs e)
        {
            NJTreeBuilder NJTree = new NJTreeBuilder(distanceMatrix);

            String NewickString = NJTree.generateTreeInNewickFormat(richBox_DistanceMatrixsSets);
            label_NewickFormat.Text = NewickString;
            
            var elements = webBrowser1.Document.GetElementsByTagName("textarea");         
            foreach (HtmlElement element in elements)
            {
                // If there's more than one button, you can check the
                //element.InnerHTML to see if it's the one you want
                element.InnerText = NewickString;
            }

            foreach (HtmlElement form in webBrowser1.Document.Forms)
                form.InvokeMember("submit");
        }

        private void wczytajDomyslnaMacierzButton_Click(object sender, EventArgs e)
        {
            Dictionary<string, Dictionary<string, double>> distances = new Dictionary<string, Dictionary<string, double>>();
                string[] lines;
                using (StreamReader sr = new StreamReader(@"../../distances01.txt"))
                {
                    lines = sr.ReadToEnd().Replace("\r", "").Split('\n');
                }
                string[] taxas = lines[0].Split('\t');

                podobienstwa_dgv.ColumnCount = taxas.Length + 1;
                podobienstwa_dgv.RowCount = taxas.Length + 1;

                for (int i = 1; i < taxas.Length; i++)
                {
                    distances.Add(taxas[i], new Dictionary<string, double>());
                    podobienstwa_dgv[i, 0].Value = taxas[i];
                    podobienstwa_dgv[0, i].Value = taxas[i];
                }

                StyleDistanceMatrixTable();

                int column = 1;
                foreach (string taxon in distances.Keys)
                {
                    string[] lineValues = lines[column].Split('\t');
                    int j = 1;
                    foreach (string taxon2 in distances.Keys)
                    {

                        distances[taxon].Add(taxon2, Double.Parse(lineValues[j]));
                        podobienstwa_dgv[column, j].Value = Double.Parse(lineValues[j]);
                        j++;
                    }
                    j = 1;
                    column++;
                }

                distanceMatrix = distances;

        }

        private void StyleDistanceMatrixTable()
        {
            foreach (DataGridViewColumn column in podobienstwa_dgv.Columns)
            {
                column.Width = 30;
            }
        }

        private void podobienstwa_btn_Click(object sender, EventArgs e)
        {
            //IDictionary<char, IDictionary<char, double>> podobienstwa = new Dictionary<char, IDictionary<char, double>>();

            //foreach (char c1 in alfabet)
            //{
            //    podobienstwa[c1] = new Dictionary<char, double>();
            //}
            //for (int i = 1; i < alfabet.Count + 1; i++)
            //{
            //    char row_letter = podobienstwa_dgv[0, i].Value.ToString().ToCharArray()[0];
            //    for (int j = 1; j < alfabet.Count + 1; j++)
            //    {
            //        char column_letter = podobienstwa_dgv[j, 0].Value.ToString().ToCharArray()[0];
            //        podobienstwa[row_letter][column_letter] = Double.Parse(podobienstwa_dgv[j, i].Value.ToString());
            //    }
            //}

            //narzedzia = new SekwencjeNarzedzia(podobienstwa, alfabet);

            ////inicjalizuj_alfabet.Enabled = false;
            ////dodaj_sekwencje.Enabled = true;
            //sklej_sekwencje.Enabled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            podobienstwa_btn_Click(sender, e);
            List<String> linieDoPliku = new List<String>();
            for (int i = 0; i < podobienstwa_dgv.Rows.Count; i++)
            {
                String linia = "";
                for (int j = 0; j < podobienstwa_dgv.Columns.Count; j++)
                {
                    linia += podobienstwa_dgv[j, i].Value;
                    linia.Replace("\r", "");
                    if (j != podobienstwa_dgv.Columns.Count - 1) linia += '\t';
                }
                linieDoPliku.Add(linia);
            }
            using (StreamWriter outfile = new StreamWriter("..\\..\\podobienstwa.txt", false))
            {
                foreach (String linia in linieDoPliku)
                {
                    outfile.WriteLine(linia);
                }
            }
        }

        private void podobienstwa_dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell cell = podobienstwa_dgv[e.ColumnIndex, e.RowIndex];
            DataGridViewCell oppositeCell = podobienstwa_dgv[e.RowIndex, e.ColumnIndex];
            oppositeCell.Value = cell.Value;

            float distance = float.Parse(cell.Value.ToString());

            Dictionary<string, double> d1 = distanceMatrix[podobienstwa_dgv[0, e.ColumnIndex].Value.ToString()];
            d1[podobienstwa_dgv[e.RowIndex, 0].Value.ToString()] = distance;

            Dictionary<string, double> d2 = distanceMatrix[podobienstwa_dgv[e.RowIndex, 0].Value.ToString()];
            d2[podobienstwa_dgv[0, e.ColumnIndex].Value.ToString()] = distance;
            
        }
    }


}
